var express = require('express');
var app = express();
app.use('/public', express.static('public'));
var conf = require('./conf');
var http = require("http");
var md5 = require('md5-node');

var env = 'local';// 默认 local
var redis = require('redis');

var index = 0;

function getConnect() {
    var {host, port, password} = conf[env];
    var connection = redis.createClient(port, host);
    if (!!password) {
        connection.auth(password);
    }
    connection.select(index, function (err, result) {
    });
    return connection;
}

function syncQuery(sql, connection) {
    // 返回一个 Promise
    return new Promise((resolve, reject) => {
        connection.query(sql, (err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(result)
            }
        })
    })
}

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};

app.get('/', function (req, res) {
    res.sendFile(__dirname + "/" + "index.html");
});

app.get('/changeDB', function (req, res) {
    index = req.query.index;
    res.end("OK");
});

app.get('/queryEnv', function (req, res) {
    var data = {};
    data.env = env;
    data.envList = [];
    for (var e in conf) {
        data.envList.push(e);
    }
    console.log('--queryEnv--');
    console.log(data);
    console.log('----');
    res.end(JSON.stringify(data));
});

app.get('/changeEnv', function (req, res) {
    env = req.query.env;
    console.log('--changeEnv--' + env);
    res.end(JSON.stringify({env: env}));
});

app.get('/keys', function (req, res) {

    let key = req.query.key;
    console.log('--keys--' + key);

    let client = getConnect();

    client.keys(key, function (err, result) {
        console.log(key, result);
        res.end(JSON.stringify(result));
    });
});

app.get('/set', function (req, res) {

    console.log('--set--');
    console.log(req.query);

    let name = req.query.name;
    let value = req.query.value;

    let client = getConnect();
    client.set(name, value, function (err, result) {
        console.log(result);
        res.end(result);
    });
});

app.get('/get', function (req, res) {
    let name = req.query.name;
    console.log('--get--' + name);

    let client = getConnect();
    client.get(name, function (err, result) {
        console.log(name, result);
        res.end(result);
    });
});

app.get('/del', function (req, res) {
    let name = req.query.name;
    console.log('--del--' + name);

    let client = getConnect();
    client.del(name, function (err, result) {
        console.log(name, result);
        res.end("ok");
    });
});

app.get('/ttl', function (req, res) {
    let name = req.query.name;
    console.log('--ttl--' + name);

    let client = getConnect();
    client.ttl(name, function (err, result) {
        console.log(name, result);
        res.end(result + '');
    });
});

app.get('/tool', function (req, res) {
    res.sendFile(__dirname + "/" + "tool.html");
});

let key = "uWwjeEKsri";

app.get('/passport', function (req, res) {
    let uid = req.query.uid;
    let last = req.query.last;
    let url = "http://passport2.chaoxing.com/api/userinfo?uid=" + uid + "&enc=" + md5(uid+key) + "&last="+last;

    http.get(url, function (data) {
        var str = "";
        data.on("data", function (chunk) {
            str += chunk;//监听数据响应，拼接数据片段
        });
        data.on("end", function () {
            console.log(str.toString());
            //这里指定编码，处理乱码的问题
            res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
            res.end(str.toString());
        });
    });
});

app.get('/schoolinfo', function (req, res) {
    let schoolid = req.query.schoolid;
    let url = "http://passport2-api.chaoxing.com/api/schoolinfo?schoolid=" + schoolid + "&enc=" + md5(schoolid+key);

    http.get(url, function (data) {
        var str = "";
        data.on("data", function (chunk) {
            str += chunk;//监听数据响应，拼接数据片段
        });
        data.on("end", function () {
            console.log(str.toString());
            //这里指定编码，处理乱码的问题
            res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
            res.end(str.toString());
        });
    });
});


var server = app.listen(8082, function () {
    var host = "localhost";
    var port = server.address().port;
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
});